package cn.bugstack.config;

import cn.bugstack.infrastructure.gateway.IGroupBuyMarketService;
import cn.bugstack.infrastructure.gateway.IWeixinApiService;
import cn.bugstack.infrastructure.gateway.TokenHeaderInterceptor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description
 * @create 2024-02-25 12:05
 */
@Slf4j
@Configuration
public class Retrofit2Config {

    //微信支付接口
    private static final String BASE_URL = "https://api.weixin.qq.com/";

    //拼团营销的接口地址
    @Value("${app.config.group-buy-market.api-url}")
    private  String groupBuyMarketApiUrl;

    @Bean
    public Retrofit retrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
    }

    @Bean
    public IWeixinApiService weixinApiService(Retrofit retrofit) {
        return retrofit.create(IWeixinApiService.class);
    }


    @Bean
    public IGroupBuyMarketService groupBuyMarketService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(groupBuyMarketApiUrl)
                .client(getClient().build())
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(IGroupBuyMarketService.class);
    }



    private OkHttpClient.Builder getClient() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(15, TimeUnit.SECONDS);
        httpClientBuilder.addNetworkInterceptor(new TokenHeaderInterceptor());
        return httpClientBuilder;
    }

}
